# gozerbot/gozertest.py
#
#

""" bot commands tests """

__copyright__ = 'this file is in the public domain'

from gozerbot.ircevent import Ircevent
from gozerbot.generic import calledfrom
import re, Queue, sys

class Gozertest(object):

    """ a gozertest """

    def __init__(self, txt, regex, plugname=None):
        self.txt = txt
        self.regex = regex
        self.results = []
        self.plugname = plugname

    def check(self, bot, ievent):
        """ do test """
        self.results = []
        event = Ircevent()
        event.copyin(ievent)
        q = Queue.Queue()
        event.queues.append(q)
        event.txt = self.txt
        bot.plugins.trydispatch(bot, event)
        while 1:
            result = q.get()
            if not result:
                break
            self.results.append(result)
        for i in self.results:
            if re.search(self.regex, i):
                return 1

    def __str__(self):
        return "txt: %s .. regex: %s .. results: %s " % (self.txt, self.regex, \
' .. '.join(self.results))

class Gtests(object):

    """ all the gozertests """

    def __init__(self):
        self.tests = []
        self.failed = []
        self.ok = []

    def add(self, txt, regex):
        """ add test """
        plugname = calledfrom(sys._getframe())
        self.tests.append(Gozertest(txt, regex, plugname))

    def rmtests(self, plugname):
        """ remove tests in plugin """
        for i in range(len(self.tests) -1, -1, -1):
            if self.tests[i].plugname == plugname:
                del self.tests[i]
    
    def dotests(self, bot, ievent):
        """ do the tests """
        self.failed = []
        self.ok = [] 
        nrtests = 0
        for i in self.tests:
            result = i.check(bot, ievent)
            nrtests += 1
            if not result:
                self.failed.append(i)
            else:
                self.ok.append(i)
        ievent.reply("nrtests: %s ok: %s failed: %s" % (nrtests, \
len(self.ok), len(self.failed)))
        resultstr = ""
        for i in self.failed:
            resultstr += "+++ %s " % str(i)
        ievent.reply(resultstr)

gtest = Gtests()
